import Vue from 'vue';
import Vuex from 'vuex';
import user from './modules/user';
import dictionary from './modules/dictionary';
import { switchUserLanguage } from '@/api/language';

const Message = require('poros/ui/lib/message').default;

// 默认语言
const LANGUAGE_DEFAULT = 'zh_CN';
// 语言缓存 key
const LANGUAGE_CACHE_KEY = 'poros-language';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    // 语言 zh_CN: 中文 en_US: 英文
    language: LANGUAGE_DEFAULT,
    spinning: false,
  },
  getters: {
    language(state) {
      console.log('state: ', state);
      return state.language;
    },
    spinning(state) {
      return state.spinning;
    },
  },
  mutations: {
    setLanguage(state, data) {
      state.language = data;
    },
    setSpinning(state, data) {
      state.spinning = data;
    },
  },
  actions: {
    // 切换语言，当前仅 支持 中英文切换
    switchLanguage(store) {
      const language = store.state.language === 'zh_CN' ? 'en_US' : 'zh_CN';

      switchUserLanguage({
        language: language.replace('_', '-'),
      })
        .then(res => {
          if (res.code === 0) {
            store.commit('setLanguage', language);

            localStorage.setItem(LANGUAGE_CACHE_KEY, language);
          } else {
            throw new Error(res.msg);
          }
        })
        .catch(err => {
          Message.error(err.message);
        });
    },
    getLanguageCache(store) {
      const language = localStorage.getItem(LANGUAGE_CACHE_KEY);

      if (language) {
        store.commit('setLanguage', language.replace('-', '_'));
      }
    },
  },
  modules: {
    user,
    dictionary,
  },
});
